const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const AfterSalesList = require('../db/AfterSalesList'); // 你的模型

// 获取列表（支持分页、搜索）
router.get('/list', async (req, res) => {
    const { page = 1, pageSize = 10, search = '' } = req.query;
    const query = search
        ? { $or: [{ desc: { $regex: search, $options: 'i' } }] }
        : {};
    const total = await AfterSalesList.countDocuments(query);
    const data = await AfterSalesList.find(query)
        .sort({ _id: 1 })
        .skip((page - 1) * pageSize)
        .limit(Number(pageSize));
    res.json({ code: 0, data, total });
});

// 新增
router.post('/add', async (req, res) => {
    try {
        const item = new AfterSalesList(req.body);
        await item.save();
        res.json({ code: 0, msg: '添加成功' });
    } catch (e) {
        res.json({ code: 1, msg: '添加失败', error: e });
    }
});

// 删除
router.delete('/delete', async (req, res) => {
    const { _id } = req.query;
  
    await AfterSalesList.deleteOne({_id});
    res.json({ code: 0, msg: '删除成功' });
});

// 编辑
router.put('/update', async (req, res) => {
    const { id, ...rest } = req.body;
    await AfterSalesList.findByIdAndUpdate(id, rest);
    res.json({ code: 0, msg: '更新成功' });
});

module.exports = router;
